const CKEditorWebpackPlugin = require('@ckeditor/ckeditor5-dev-webpack-plugin');
const {
	styles
} = require('@ckeditor/ckeditor5-dev-utils');
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');

module.exports = {
	// The source of CKEditor is encapsulated in ES6 modules. By default, the code
	// from the node_modules directory is not transpiled, so you must explicitly tell
	// the CLI tools to transpile JavaScript files in all ckeditor5-* modules.
	transpileDependencies: [
		/ckeditor5-[^/\\]+[/\\]src[/\\].+\.js$/,
	],

	configureWebpack: {
		plugins: [
			// CKEditor needs its own plugin to be built using webpack.
			new CKEditorWebpackPlugin({
				// See https://ckeditor.com/docs/ckeditor5/latest/features/ui-language.html
				language: 'en'
			}),

			new PrerenderSPAPlugin({
				// 生成文件的路径，也可以与webpakc打包的一致。
				// 下面这句话非常重要！！！
				// 这个目录只能有一级，如果目录层次大于一级，在生成的时候不会有任何错误提示，在预渲染的时候只会卡着不动。
				staticDir: path.join(__dirname, 'dist'),
				// 对应自己的路由文件，比如a有参数，就需要写成 /a/param1。
				routes: ['/', '/product', '/about'],
				// 这个很重要，如果没有配置这段，也不会进行预编译
				renderer: new Renderer({
					inject: {
						foo: 'bar'
					},
					headless: false,
					// 在 main.js 中 document.dispatchEvent(new Event('render-event'))，两者的事件名称要对应上。
					renderAfterDocumentEvent: 'render-event'
				})
			}),
		]
	},

	css: {
		loaderOptions: {
			// Various modules in the CKEditor source code import .css files.
			// These files must be transpiled using PostCSS in order to load properly.
			postcss: styles.getPostCssConfig({
				themeImporter: {
					themePath: require.resolve('@ckeditor/ckeditor5-theme-lark')
				},
				minify: true
			})
		}
	},

	chainWebpack: config => {
		// Vue CLI would normally use its own loader to load .svg files. The icons used by
		// CKEditor should be loaded using raw-loader instead.

		// Get the default rule for *.svg files.
		const svgRule = config.module.rule('svg');

		// Then you can either:
		//
		// * clear all loaders for existing 'svg' rule:
		//
		//		svgRule.uses.clear();
		//
		// * or exclude ckeditor directory from node_modules:
		svgRule.exclude.add(__dirname + '/node_modules/@ckeditor');

		// Add an entry for *.svg files belonging to CKEditor. You can either:
		//
		// * modify the existing 'svg' rule:
		//
		//		svgRule.use( 'raw-loader' ).loader( 'raw-loader' );
		//
		// * or add a new one:
		config.module
			.rule('cke-svg')
			.test(/ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/)
			.use('raw-loader')
			.loader('raw-loader');
	}
};
